
package com.yanboo.modules.system.rest;

import cn.hutool.core.collection.CollectionUtil;
import com.yanboo.common.annotation.CustomController;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import com.yanboo.logging.annotation.Log;
import com.yanboo.common.exception.BadRequestException;
import com.yanboo.modules.system.domain.Dept;
import com.yanboo.modules.system.service.DeptService;
import com.yanboo.modules.system.service.dto.DeptDto;
import com.yanboo.modules.system.service.dto.DeptQueryCriteria;
import com.yanboo.common.utils.PageResult;
import com.yanboo.common.utils.PageUtil;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import jakarta.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 系统：部门管理
 */
@Tag(name = "系统：部门管理")
@CustomController
@RequiredArgsConstructor
@RequestMapping("/api/dept")
public class DeptController {

    private final DeptService deptService;
    private static final String ENTITY_NAME = "dept";

    /**
     * 导出部门数据
     * @param response
     * @param criteria
     * @throws Exception
     */
    @Operation(summary = "导出部门数据")
    @GetMapping(value = "/download")
    public void exportDept(HttpServletResponse response, DeptQueryCriteria criteria) throws Exception {
        deptService.download(deptService.queryAll(criteria, false), response);
    }

    /**
     * 查询部门
     * @param criteria
     * @return
     * @throws Exception
     */
    @Operation(summary = "查询部门")
    @GetMapping
    public ResponseEntity<PageResult<DeptDto>> queryDept(DeptQueryCriteria criteria) throws Exception {
        List<DeptDto> depts = deptService.queryAll(criteria, true);
        return new ResponseEntity<>(PageUtil.toPage(depts, depts.size()),HttpStatus.OK);
    }

    /**
     * 查询部门:根据ID获取同级与上级数据
     * @param ids
     * @param exclude
     * @return
     */
    @Operation(summary = "查询部门",description = "根据ID获取同级与上级数据")
    @PostMapping("/superior")
    public ResponseEntity<PageResult<DeptDto>> getDeptSuperior(@RequestBody List<Long> ids,
                                                  @RequestParam(defaultValue = "false") Boolean exclude) {
        Set<DeptDto> deptSet  = new LinkedHashSet<>();
        for (Long id : ids) {
            DeptDto deptDto = deptService.findById(id);
            List<DeptDto> depts = deptService.getSuperior(deptDto, new ArrayList<>());
            if(exclude){
                for (DeptDto dept : depts) {
                    if(dept.getId().equals(deptDto.getPid())) {
                        dept.setSubCount(dept.getSubCount() - 1);
                    }
                }
                // 编辑部门时不显示自己以及自己下级的数据，避免出现PID数据环形问题
                depts = depts.stream().filter(i -> !ids.contains(i.getId())).collect(Collectors.toList());
            }
            deptSet.addAll(depts);
        }
        return new ResponseEntity<>(deptService.buildTree(new ArrayList<>(deptSet)),HttpStatus.OK);
    }

    /**
     * 新增部门
     * @param resources
     * @return
     */
    @Operation(summary = "新增部门")
    @Log("新增部门")
    @PostMapping
    public ResponseEntity<Object> createDept(@Validated @RequestBody Dept resources){
        if (resources.getId() != null) {
            throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
        }
        deptService.create(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    /**'
     * 修改部门
     * @param resources
     * @return
     */
    @Operation(summary = "修改部门")
    @Log("修改部门")
    @PutMapping
    public ResponseEntity<Object> updateDept(@Validated(Dept.Update.class) @RequestBody Dept resources){
        deptService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除部门
     * @param ids
     * @return
     */
    @Operation(summary = "删除部门")
    @Log("删除部门")
    @DeleteMapping
    public ResponseEntity<Object> deleteDept(@RequestBody Set<Long> ids){
        Set<DeptDto> deptDtos = new HashSet<>();
        for (Long id : ids) {
            List<Dept> deptList = deptService.findByPid(id);
            deptDtos.add(deptService.findById(id));
            if(CollectionUtil.isNotEmpty(deptList)){
                deptDtos = deptService.getDeleteDepts(deptList, deptDtos);
            }
        }
        // 验证是否被角色或用户关联
        deptService.verification(deptDtos);
        deptService.delete(deptDtos);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}